/**
 * access的使用
 */
const config = require('../config');
const path = require('path')
const fs = require('fs');
const rp = require('request-promise-native');

class Wechat {
    constructor() {
    }
    /**
     * 获取token
     */
    getAccess() {
        var url = `${config.assessToken_url}&appid=${config.appId}&secret=${config.secret}`;
        //发送请求
        return new Promise((resolve, reject) => {
            rp({ method: 'GET', url, json: true })
                .then(res => {
                    res.expires_in = Date.now() + (res.expires_in - 300) * 1000;
                    resolve(res);
                }).catch(err => {
                    reject(err);
                })
        })
    }
    /**
     * 保存数据
     */
    saveAccess(accessdata) {
        return new Promise((resolve, reject) => {
            fs.writeFile(path.join(__dirname, 'accessToken.txt'), JSON.stringify(accessdata), err => {
                if (!err) {
                    resolve()
                } else {
                    reject(err)
                }
            })
        })
    }
    /**
     *  读取文件
     */
    readAccess() {
        return new Promise((resolve, reject) => {
            fs.readFile(path.join(__dirname, 'accessToken.txt'), (err, data) => {
                if (!err) {
                    if (data == '') {
                        reject(err)
                    } else {
                        resolve(JSON.parse(data))
                    }

                } else {
                    reject(err)
                }
            })
        })
    }
    /**
     * 判断Access是否有效
     */
    isAccess(data) {
        if (!data && !data.access_token && !data.expires_in) {
            return false;
        }
        if (data.expires_in < Date.now()) {
            return false;
        } else {
            return true;
        }
    }
    /**
     * 获得正确的Access的值
     */
    returnAccess() {
        if (this.expires_in && this.access_token && this.isAccess(this)) {
            return Promise.resolve({
                expires_in: this.expires_in,
                access_token: this.access_token
            })
        }
        return this.readAccess()
            .then(async res => {
                if (!this.isAccess(res)) {
                    const val = await this.getAccess()
                    await this.saveAccess(val)
                    return Promise.resolve(val)
                } else {
                    return Promise.resolve(res)
                }
            })
            .catch(async err => {
                const val = await this.getAccess()
                await this.saveAccess(val)
                return Promise.resolve(val)
            })
            .then(res => {
                this.access_token = res.access_token;
                this.expires_in = res.expires_in;
                return Promise.resolve(res)
            })
    }

}

module.exports = new Wechat()